<?php

namespace App\Http\Controllers\Company;

use App\Facades\Site;
use App\Http\Requests\Common\Captcha\EmailSendRequest;
use App\Http\Requests\Common\Captcha\MobileRequest;
use App\Http\Requests\Common\Captcha\MobileSmsRequest;
use App\Models\Company\CompanyUser;
use App\Http\Requests\Company\ModPassword\ModPasswordRequest;
use Illuminate\Http\Request;
use Style, Mail, Hash, Crypt, Sms, CustomPassword;
use Illuminate\Hashing\BcryptHasher as Hasher;


class CompanyUserController extends CommonController{
    protected $hasher;

    public function __construct(Hasher $hasher){
        $this->hasher = $hasher;
    }
    //------------------------------------------------------------------------------------------------------------------
    /**
     * 账号设置
     * @param Request $request
     * @return mixed
     */
    public function setAccount(Request $request){
        $user = auth()->guard('company')->user();
        //获取邮箱
        if(!empty($user->email)){
            $list = explode('@', $user->email);
            $user->stremail = substr_replace($list[0], '****', 2, 4) . (!empty($list[1]) ? '@' . $list[1] : '');
        }else{
            $user->stremail = '';
        }
        //获取手机
        if(!empty($user->mobile)){
            $user->strmobile = substr_replace($user->mobile, '****', 2, 4);;
        }else{
            $user->strmobile = '';
        }
        return Style::view('company.setAccount', compact('user'));
    }

    /**
     * ajax验证验证码
     * @param Request $request
     */
    public function ajaxCode(Request $request){
        $code = strtolower($request->input('code'));
        $captcha = session('captcha.key');
        //验证哈希验证码
        echo ($this->hasher->check($code, $captcha)) ? 'true' : 'false';
    }

    /**
     * 邮箱发送
     * @param EmailSendRequest $request
     * @return mixed
     */
    public function emailSend(EmailSendRequest $request){
        $user = auth()->guard('company')->user();
        $key = env('APP_KEY');
        $email = Crypt::encrypt($request->email);
        $user->mail_link = '?uid=' . $user->uid . '&email=' . $email . '&key=' . bcrypt($user->uid . $user->username . $key);
        if(!empty(Site::get('MailAddress'))){
            $result = Mail::send('emails.company_bind_email', ['user' => $user], function($m) use ($request){
                $m->from(Site::get('MailAddress'), Site::get('webname'));
                $m->to($request->email)->subject(Site::get('webname') . '邮箱绑定');
            });
            return $result;
        }else{
            return false;
        }
    }

    /**
     * 邮箱激活
     * @param Request $request
     * @return mixed
     */
    public function activationMail(Request $request){
        $user = CompanyUser::where('uid', $request->uid)->first(['uid', 'email', 'username']);
        $key = env('APP_KEY');
        $email = Crypt::decrypt($request->email);
        //验证绑定邮箱激活是不是成功
        if(Hash::check($user->uid . $user->username . $key, $request->key)){
            $result = CompanyUser::where('uid', $user->uid)->update(['email_id' => 1, 'email' => $email]);
            if($result){
                return Style::view('company.bindEmailSuccess', compact('user'));
            }else{
                return Style::view('company.bindEmailError');
            }
        }else{
            return Style::view('company.bindEmailError');
        }
    }

    /**
     * 获取短信验证码
     * @param MobileRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxComCode(MobileRequest $request){
        $mobileNum = $request->input('mobile');
        $result = CompanyUser::where('mobile', $mobileNum)->where('mobile_id', 1)->first();
        if($result){
            return response()->json(['status' => '2', 'msg' => '此手机号码已经绑定']);
        }else{
            //设置session
            $request->session()->put('mobile_verification_code', rand(1000, 9999));
            $request->session()->put('mobile_verification', $mobileNum);
            //模板参数
            $smsParam = array(
                'product' => Site::get('webname'),
                'code' => (string)session('mobile_verification_code')
            );
            $sendResult = Sms::codeSend($mobileNum, $smsParam);
            //返回对象
            if(is_object(@$sendResult->result) && $sendResult->result->err_code == '0'){
                return response()->json(['status' => '1', 'msg' => '发送短信成功']);
            }else{
                return response()->json(['status' => '0', 'msg' => '一分钟之内只能发一次,或者您发送的次数已经达到上限']);
            }
        }
    }

    /**
     * ajax验证获取短信码
     * @param Request $request
     */
    public function ajaxComSms(Request $request){
        $mcode = $request->input('mcode');
        $mobile = $request->input('mobile');
        //判断手机是不是被注册
        echo ($mcode == session('mobile_verification_code') && $mobile == session('mobile_verification')) ? 'true' : 'false';
    }

    /**
     * 手机绑定
     * @param MobileSmsRequest $request
     * @return array
     */
    public function bindMobile(MobileSmsRequest $request){
        $user = auth()->guard('company')->user();
        //判断手机是不是被绑定了
        $companyUser = CompanyUser::where('mobile', $request->mobile)->where('uid','!=',$user->uid)->first();
        if($companyUser){
            return response()->json(['status' => 1, 'msg' => '此手机号码已经被注册，不能绑定！']);
        }else{
            $result = CompanyUser::where('uid', $user->uid)->update(['mobile_id' => 1, 'mobile' => $request->mobile]);
            if($result){
                //删除验证码的session数据
                $request->session()->forget('mobile_verification');
                $request->session()->forget('mobile_verification_code');
                return response()->json(['status' => 0, 'msg' => '手机绑定成功！']);
            }else{
                return response()->json(['status' => 1, 'msg' => '手机绑定失败，请稍后重试！']);
            }
        }
    }

    /**
     * 取消QQ绑定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelBindQq(Request $request){
        $user = auth()->guard('company')->user();
        if(!empty($user)){
            $result = CompanyUser::where('uid', $user->uid)->update(['qqopenid' => null,'updatetime'=>date('Y-m-d H:i:s',time())]);

            if($result){
                return response()->json(['status' => 0, 'msg' => '取消QQ绑定成功！']);
            }else{
                return response()->json(['status' => 1,'msg' => '取消QQ绑定失败，请稍后重试！']);
            }
        }else{
            return response()->json(['status' => 1, 'msg' => '取消QQ绑定失败！请稍后重试']);
        }
    }

    /**
     * 取消微信绑定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel_wxbind(Request $request){
        $user = auth()->guard('company')->user();
        if(!empty($user)){
            $result = CompanyUser::where('uid', $user->uid)->update(['wechatopenid' => null, 'wechatmpopenid' => null,
                'wechatunionid' => null,'updatetime'=>date('Y-m-d H:i:s',time())]);
            if($result){
                return response()->json(['status' => 0, 'msg' => '取消微信绑定成功！']);
            }else{
                return response()->json(['status' => 1, 'msg' => '取消微信绑定失败！请稍后重试']);
            }
        }else{
            return response()->json(['status' => 1, 'msg' => '取消微信绑定失败！请稍后重试']);
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    /**
     * 修改密码
     * @param Request $request
     * @return mixed
     */
    public function modPassword(Request $request){
        $user = auth()->guard('company')->user();
        $uid = $user->uid;
        return Style::view('company.modPassword', compact('uid'));
    }

    /**
     * 修改密码提交
     * @param ModPasswordRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postModPassword(ModPasswordRequest $request){
        $user = auth()->guard('company')->user();
        $input['password'] = CustomPassword::make($request->input('password'));
        CompanyUser::where('uid', $user->uid)->update($input);
        return redirect('company/welcome');
    }

    /**
     * 修改密码提交
     * @param Request $request
     */
    public function ajaxPass(Request $request){
        $user = auth()->guard('company')->user();
        $password = CompanyUser::where('uid', $user->uid)->first(['password'])->password;
        //判断旧密码是不是正确
        echo (CustomPassword::check($request->input('oldpassword'), $password)) ? 'true' : 'false';
    }
}